package com.coder4j.controller;

import com.coder4j.service.FileStorageService;
import com.coder4j.starter.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@Slf4j
@RestController
@RequestMapping("/file")
@CrossOrigin
public class ImageUploadController {

    @Autowired
    private FileStorageService fileStorageService;

    @Value("${app.upload.dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public R uploadImage(@RequestParam("file") MultipartFile file) {
        // System.out.println("文件名称："+file.getOriginalFilename());
        String fileUrl = fileStorageService.storeFile(file);
        return R.success(fileUrl);
    }

    @GetMapping("/images/{fileUrl}")
    public ResponseEntity<byte[]> getImage(@PathVariable(name = "fileUrl") String fileUrl) {
        // 拼接图片完整路径
        File imageFile = new File(uploadDir, fileUrl);

        // 检查文件是否存在
        if (!imageFile.exists() || !imageFile.isFile()) {
            return ResponseEntity.notFound().build(); // 如果文件不存在，返回 404
        }

        try {
            // 读取图片文件为字节数组
            byte[] imageBytes = Files.readAllBytes(imageFile.toPath());

            // 返回图片数据，并设置 Content-Type
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG) // 根据实际图片类型调整
                    .body(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build(); // 内部服务器错误
        }
    }


}
